<script setup lang="ts">
import {onMounted, ref} from "vue";

import {bytesToSize} from "../../../common/util/byteUtil";

const wdList = ref([]);

const zzzhgs = ref(false)

function selectWd() {
  window.api.selectFile();
}

function selectWjj() {
  window.api.selectFileByWjj();
}

window.api.on("addItems", (e, items) => {
  wdList.value.push(...items.map(x => ({...x, dyzt: "dengdai"})));
});

const tableRef = ref();

function removeItem() {
  const selections = tableRef.value.getSelectionRows();

  for (let i = 0; i < wdList.value.length; i++) {
    if (selections.includes(wdList.value[i])) {
      wdList.value.splice(i, 1);
      i--;
    }
  }
}

async function checkFileType(data) {
  try {
    if (!data.printFile) {
      const wjlj = data.wjjlj + "\\" + data.wjmc;
      // 判断文件类型
      // if (wjlj.endsWith(".docx") || wjlj.endsWith(".doc")) {

      zzzhgs.value = true;
      // 获取printFile
      const printFile = await window.api.getPrintFile(wjlj);
      data.printFile = printFile
    }
  } finally {
    zzzhgs.value = false;
  }
}

async function openItem(data, column, ev) {
  // myLocalStorage.setItem("dyj", dyj.value)
  // 判断是否有printFile，没有则进行转换
  await checkFileType(data)
  window.api.preview(data.printFile);
}

function handleContextmenu(row, column, ev) {
  const i = wdList.value.indexOf(row)
  const template = [
    {
      label: '删除',
      click: () => {
        const idx = wdList.value.indexOf(row)
        wdList.value.splice(idx, 1)
      }
    },
    {type: 'separator'},
    {
      label: '上移',
      enabled: i != 0,
      click: () => {
        const idx = wdList.value.indexOf(row)
        wdList.value[idx] = wdList.value[idx - 1]
        wdList.value[idx - 1] = row
      }
    },
    {
      label: '下移',
      enabled: i != wdList.value.length - 1,
      click: () => {
        const idx = wdList.value.indexOf(row)
        wdList.value[idx] = wdList.value[idx + 1]
        wdList.value[idx + 1] = row
      }
    },
  ]
  window.api.showContextMenu(template)
}

const printerList = ref([]);

const dyj = ref("");

const dySetting = ref({
  copies: 1,
  monochrome: false,
  orientation: 'portrait',
  paperSize: "A5",
  scale: "fit",
  side: "simplex",
})

onMounted(() => {
  // myLocalStorage.setItem("option", getOption());
  const option = myLocalStorage.getItem("option")
  if (option != null) {
    dySetting.value.copies = option.copies || 1
    dySetting.value.monochrome = option.monochrome || false
    dySetting.value.orientation = option.orientation || "portrait"
    dySetting.value.paperSize = option.paperSize || "A5"
    dySetting.value.scale = option.scale || "fit"
    dySetting.value.side = option.side || "simplex"
  }

  const printers = window.api.getPrinters();
  for (let printer of printers) {
    printerList.value.push({
      ...printer,
    });
    if (printer.sfmrdyj) {
      dyj.value = printer.dyjmc;
    }
  }

});

const stop = ref(false);
const sfzzdy = ref(false);
const ydysl = ref(0);

const dyztMap = {
  shibai: "打印失败",
  dengdai: "未打印",
  chenggong: "打印成功",
  jinxingzhong: "打印中",
}

async function print() {
  if (sfzzdy.value) {
    stop.value = true;
    sfzzdy.value = false;
    return
  }

  const option = dySetting.value
  myLocalStorage.setItem("option", option)

  stop.value = false
  sfzzdy.value = true;
  ydysl.value = 0;
  let sbsl = 0;
  let cgsl = 0;
  let start = Date.now()
  // const option = getOption();
  for (let valueElement of wdList.value) {
    if (stop.value) {
      break
    }
    valueElement.dyzt = "jinxingzhong";
    try {
      await checkFileType(valueElement)
      await window.api.print({
        path: valueElement.printFile,
        option: {
          printer: dyj.value,
          orientation: option.orientation,
          scale: option.scale,
          side: option.side,
          paperSize: option.paperSize,
          monochrome: option.monochrome,
          copies: option.copies,
          silent: true,
          // pages:'', 要打印的页面
          // subset:'odd', // even 偶数页  odd 奇数页
          // bin: 0, // 纸盘
          printDialog: false,
        },
      });
      valueElement.dyzt = "chenggong";
      cgsl++;
    } catch (e) {
      console.log(e)
      sbsl++;
      valueElement.dyzt = "shibai";
      valueElement.ycrz = e.message;
    }

    ydysl.value++;
  }
  sfzzdy.value = false;

  window.api.addPrintCount(cgsl)

  let xhsj = Date.now() - start

  const res = await window.api.showMessage({
    cancelButtonText: '不保留',
    size: {height: 240},
    msg: `作业已完成
      <br>
      <br>
      <div style="color: red">失败：${sbsl}</div>
      文件已发送到打印机：${cgsl}
      <br>
      已用时间：${xhsj / 1000} 秒
      <br>
      <br>
      是否需要保留成功文档？`
  })

  if (!res) {
    for (let i = 0; i < wdList.value.length; i++) {
      const valueElement = wdList.value[i]
      if (valueElement.dyzt == 'chenggong') {
        wdList.value.splice(i, 1)
        i--
      }
    }
  }
}

function showMore(msg) {
  window.api.showMessage({
    msg: `<span style="color:red">${msg}</span>`
  })
}

function openSetting() {
  window.api.openSetting();
}

window.ondragover = (ev) => {
  ev.preventDefault(); // 阻止默认行为
  ev.stopPropagation();
  ev.dataTransfer.dropEffect = "move"; // 设置可拖动的视觉效果
}

window.ondrop = (ev) => {
  ev.preventDefault();
  ev.stopPropagation();

  const pathList = [] as string[];
  for (let file of ev.dataTransfer.files) {
    pathList.push(window.api.getPathForFile(file));
  }
  window.api.addItems(pathList);
};

async function clearWdList() {
  if (!wdList.value || !wdList.value.length) {
    return
  }
  const res = await window.api.showMessage({
    size: {height: 130, width: 220},
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    msg: `是否要清空文档列表？`
  })
  if (res) {
    wdList.value = []
  }
}
</script>

<template>
  <div style="height: 100%"
       v-loading="zzzhgs&&!sfzzdy"
       element-loading-text="格式转换中，请稍后..."
       element-loading-background="rgba(122, 122, 122, 0.2)"
  >
    <div class="leftBox">
      <!--      <div>-->
      <!--        <div style="display: inline-block">-->
      <!--          <div-->
      <!--              class="leftItem addwd"-->
      <!--              :class="{ disabled: sfzzdy }"-->
      <!--              @click="selectWd"-->
      <!--          >-->
      <!--            <div class="icon"></div>-->
      <!--            <div class="text">添加文档</div>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--        <div style="display: inline-block">-->
      <!--          <div-->
      <!--              class="leftItem addwjj"-->
      <!--              :class="{ disabled: sfzzdy }"-->
      <!--              @click="selectWjj"-->
      <!--          >-->
      <!--            <div class="icon"></div>-->
      <!--            <div class="text">添加文件夹</div>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
      <div>
        <!--        <div style="display: inline-block" @click="openSetting">-->
        <!--          <div class="leftItem sz" :class="{ disabled: sfzzdy }">-->
        <!--            <div class="icon"></div>-->
        <!--            <div class="text">设置</div>-->
        <!--          </div>-->
        <!--        </div>-->
        <!--        <div style="display: inline-block">-->
        <div
            class="leftItem ksdy"
            :class="{ disabled: !wdList.length, zzdy: sfzzdy }"
            @click="print"
        >
          <div class="icon"></div>
          <div class="text" v-if="sfzzdy">暂停</div>
          <div class="text" v-else>开始打印</div>
        </div>
        <!--        </div>-->
      </div>
      <div>
        <div class="xzdyj" :class="{ disabled: sfzzdy }">
          <div class="title">设置</div>
          <div style="margin-left: 15px; margin-right: 15px; margin-top: 15px">
            <el-form label-width="60px">
              <el-form-item label="打印机">
                <el-select placeholder="请选择打印机" v-model="dyj" popper-class="dyjselect">
                  <el-option
                      :label="pointer.dyjmc"
                      :value="pointer.dyjmc"
                      :key="pointer.dyjmc"
                      v-for="pointer in printerList"
                  >
                    <div style="align-content: center">
                      <div style="font-size: 14px;font-weight: bolder"> {{ pointer.dyjmc }}
                        <el-tag style="margin-left: 15px" v-show="pointer.sfmrdyj" type="primary">默认</el-tag>
                      </div>
                      <div v-show="pointer.dyjzt==0" style="font-size: 12px;">准备就绪</div>
                      <div v-show="pointer.dyjzt==2" style="font-size: 10px;color: red">打印机出错</div>
                      <div v-show="pointer.dyjzt!=2&&pointer.dyjzt!=0" style="font-size: 10px;">{{
                          pointer.dyjzt
                        }}
                      </div>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="纸张方向">
                <el-radio-group v-model="dySetting.orientation">
                  <el-radio-button label="纵向" value="portrait"/>
                  <el-radio-button label="横向" value="landscape"/>
                </el-radio-group>
              </el-form-item>
              <!--                <el-form-item label="缩放">-->
              <!--                  <el-radio-group v-model="scale">-->
              <!--                    <el-radio-button label="无缩放" value="noscale"/>-->
              <!--                    <el-radio-button label="适应内容" value="fit"/>-->
              <!--                    <el-radio-button label="shrink" value="shrink"/>-->
              <!--                  </el-radio-group>-->
              <!--                </el-form-item>-->
              <el-form-item label="双面打印">
                <el-radio-group v-model="dySetting.side">
                  <!--          <el-radio-button label="双面打印" value="duplex" />-->
                  <el-radio-button label="单面打印" value="simplex"/>
                  <!--          <el-radio-button label="短边翻转" value="shortEdge" />-->
                  <!--          <el-radio-button label="长边翻转" value="longEdge" />-->
                </el-radio-group>
              </el-form-item>
              <el-form-item label="纸张大小">
                <el-radio-group v-model="dySetting.paperSize">
                  <el-radio-button label="A5" value="A5"/>
                  <el-radio-button label="A4" value="A4"/>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="黑白打印">
                <el-radio-group v-model="dySetting.monochrome">
                  <el-radio-button label="彩色" :value="false"/>
                  <el-radio-button label="黑白" :value="true"/>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="份数" :rules="[{ min: 1 }]">
                <el-input type="number" min="1" v-model="dySetting.copies" style="display: inline-block;width: 80px;"/>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div>
        <div class="zbdy">
          <div class="title" style="height: 30px">
            <span v-show="!sfzzdy">准备打印</span>
            <span v-show="sfzzdy" style="font-size: 14px"
            >正在打印第 {{ ydysl + 1 }} 个文档（共 {{ wdList.length }} 个）</span
            >
          </div>
          <div
              style="
              height: 20px;
              align-content: center;
              width: calc(100% - 30px);
              margin-left: 15px;
              margin-top: 5px;
            "
          >
            <!--            <el-progress :percentage="50" :indeterminate="true" :show-text="false" />-->
            <el-progress
                v-show="sfzzdy"
                :percentage="100"
                :stroke-width="15"
                striped
                striped-flow
                :show-text="false"
            />
            <div style="margin-top: 10px;font-size: 12px;" v-show="sfzzdy">
              <span v-if="zzzhgs">格式转换中</span>
              <span v-else>正在打印中</span>
            </div>
          </div>
          <div class="desc">列表中有 {{ wdList.length }} 个文档</div>
        </div>
      </div>
    </div>
    <div class="rightBox">
      <div
          style="
          height: 36px;
          display: flex;
  background-color: var(--main-color);
          align-items: center;
          color: white;
        "
          :class="{ disabled: sfzzdy }"
      >
        <span style="padding-left: 15px">文档列表</span>
        <div class="btn-box">
          <div
              class="btn"
              @click="selectWd"
          >
            <div class="icon addwd"></div>
            <div class="text">添加文档</div>
          </div>
          <div
              class="btn"
              @click="selectWjj"
          >
            <div class="icon addwjj"></div>
            <div class="text">添加文件夹</div>
          </div>
          <div
              class="btn"
              @click="removeItem"
          >
            <div class="icon ycxm"></div>
            <div class="text">移除项目</div>
          </div>
          <div
              class="btn"
              @click="clearWdList"
          >
            <div class="icon qklb"></div>
            <div class="text">清除列表</div>
          </div>
        </div>
      </div>
      <el-table
          ref="tableRef"
          height="calc(100% - 36px)"
          :data="wdList"
          @rowDblclick="openItem"
          @rowContextmenu="handleContextmenu"
          empty-text="将文件或文件夹拖拽到此处可快捷添加"
          stripe
          border
          show-overflow-tooltip
      >
        <el-table-column
            type="selection"
            label=""
            :resizable="false"
            width="30px"
        ></el-table-column>
        <el-table-column type="index" label="#" width="30px" :resizable="false"></el-table-column>
        <el-table-column type="index" label="√" width="30px" :resizable="false"
                         align="center"
                         class-name="zt"
                         :show-overflow-tooltip="false">
          <template #default="{row}">
            <div class="icon" :class="row.dyzt" :title="dyztMap[row.dyzt]"></div>
          </template>
        </el-table-column>
        <el-table-column
            label="名称"
            prop="wjmc"
            :show-overflow-tooltip="false" :resizable="false"
        >
          <template #default="{ row }">
            <div style="height: 45px; align-content: center">
              <el-tooltip effect="dark" :content="row.wjmc" placement="top">
                <div
                    style="
                    width: 100%;
                    overflow: hidden;
                    word-break: break-all;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                >
                  {{ row.wjmc }}
                </div>
              </el-tooltip>
              <div v-show="row.ycrz" style="height: 20px">
                <div class="ycrz">
                  {{ row.ycrz }}
                </div>
                <div class="moreYcrz" @click="showMore(row.ycrz)">...</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文件夹路径" prop="wjjlj" :resizable="false"></el-table-column>
        <el-table-column
            label="类型"
            prop="wjlx"
            width="60px" :resizable="false"
        ></el-table-column>
        <el-table-column
            label="大小"
            prop="wjdx"
            :formatter="({wjdx})=>bytesToSize(wjdx)"
            width="90px"
        ></el-table-column>
        <el-table-column
            label="创建日期"
            prop="rq"
            width="130px" :resizable="false"
        ></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style scoped lang="less">
.leftItem {
  height: 112px;
  width: 112px;
  vertical-align: top;
  align-content: center;
  justify-items: center;
  border-radius: 3px;
  overflow: hidden;
  background-color: var(--main-color);

  &:hover {
    background-color: var(--main-hover-color);
  }

  .icon {
    width: 48px;
    height: 48px;
    background-size: 40px 40px;
    background-repeat: no-repeat;
    background-position: center;
  }

  .text {
    color: white;
  }

  &.ksdy {
    background-color: #02a402;
    //margin-left: 15px;
    width: 100%;
    height: 60px;
    align-content: center;
    text-align: center;

    &:hover {
      background-color: #19bc19;
    }

    .icon {
      margin-top: 6px;
      margin-right: 5px;
      vertical-align: top;
      display: inline-block;
      background-image: url("../assets/images/ksdy.svg");
    }

    .text {
      font-size: 18px;
      font-weight: bold;
      line-height: 60px;
      display: inline-block;
      vertical-align: top;
    }
  }
}

.xzdyj {
  //height: 140px;
  background-color: white;
  margin-top: 15px;
  margin-bottom: 15px;
  color: #333;
  border-radius: 5px;
  overflow: hidden;
  border: 1px solid #c3d3e9;
  box-sizing: border-box;
}

.zbdy {
  height: 140px;
  background-color: #ffffff;
  margin-top: 15px;
  margin-bottom: 15px;
  box-sizing: border-box;
  border: 1px solid #c3d3e9;
  border-radius: 5px;
  overflow: hidden;

  .desc {
    height: calc(100% - 40px - 15px - 35px);
    padding-left: 15px;
    align-content: end;
  }
}

.zbdy,
.xzdyj {
  .title {
    padding-top: 15px;
    margin-left: 15px;
  }
}

.leftBox {
  width: calc(112px + 15px + 112px);
  box-sizing: border-box;
  //margin: 15px;
  margin-right: 15px;
  //width: 303px;
  display: inline-block;
  height: 100%;
  //overflow-y: auto;
}

.rightBox {
  width: calc(100% - (112px + 15px + 112px) - 15px);
  box-sizing: border-box;
  //margin: 15px 15px 15px 0;
  display: inline-block;
  vertical-align: top;
  border: 1px solid #c3d3e9;
  height: 100%;
  background-color: #ffffff;
  border-radius: 5px;
  overflow: hidden;

  :deep(.el-table__empty-text) {
    font-size: 18px;
    font-weight: bolder;
    border: 1px dashed #ccc;
  }

  :deep(.zt) {
    .cell {
      padding-left: 0;
      padding-right: 0;
      justify-items: center;

      .icon {
        height: 24px;
        width: 24px;
        background-position: center;
        background-size: 80%;
        background-repeat: no-repeat;

        &.chenggong {
          background-image: url("../assets/images/chenggong.svg");
        }

        &.dengdai {
          background-size: 100%;
          background-image: url("../assets/images/dengdai.svg");
        }

        &.shibai {
          background-image: url("../assets/images/shibai.svg");
        }

        &.jinxingzhong {
          background-size: 70%;
          background-image: url("../assets/images/jinxingzhong.svg");
        }
      }
    }
  }

  .btn-box {
    flex: 1;
    text-align: end;
    padding-right: 15px;
    height: 100%;

    .btn {
      display: inline-block;
      width: 118px;
      height: 100%;
      //align-content: center;
      text-align: center;

      .icon {
        width: 18px;
        height: 18px;
        margin-right: 5px;
        display: inline-block;
        box-sizing: border-box;
        background-image: url("../assets/images/sch.svg");
        background-size: 18px 18px;
        background-position: center;
        background-repeat: no-repeat;
        margin-top: 9px;

        &.addwd {
          background-image: url("../assets/images/addwd.svg");
        }

        &.addwjj {
          background-image: url("../assets/images/addwjj.svg");
        }

        &.ycxm {
          background-image: url("../assets/images/sch.svg");
        }

        &.qklb {
          background-image: url("../assets/images/qk.svg");
        }
      }

      .text {
        display: inline-block;
        vertical-align: top;
        line-height: 36px;
      }


      &:hover {
        background-color: var(--main-hover-color);
      }
    }
  }
}


.ycrz {
  display: inline-block;
  color: red;
  max-width: calc(100% - 25px);
  overflow: hidden;
  height: 100%;
}

.moreYcrz {
  vertical-align: top;
  display: inline-block;
  width: 20px;
  height: 100%;
  background-color: #0f79d7;
  color: white;
  text-align: center;
  border-radius: 3px;
  margin-left: 5px;
  box-sizing: border-box;

  &:hover {
    opacity: 0.7;
  }
}

.disabled {
  background-color: #7494af !important;
  pointer-events: none;
}

.zzdy {
  background-color: #f3a002 !important;

  &:hover {
    background-color: #ffb91b !important;
  }
}

//@media (max-width: 720px) {
//  .leftBox {
//    width: calc(112px + 15px + 112px);
//  }
//
//  .rightBox {
//    width: calc(100% - (112px + 15px + 112px) - 15px);
//  }
//
//  .leftItem {
//    height: 112px;
//    width: 112px;
//  }
//}

//@media (max-height: 690px) {
//  //.leftBox {
//  //  width: calc(112px + 15px + 112px);
//  //}
//
//  //.rightBox {
//  //  width: calc(100% - (112px + 15px + 112px) - 15px);
//  //}
//
//  .leftItem {
//    height: 112px;
//    width: 112px;
//  }
//}
</style>
